<template>
	<div class="content-box">
		<TreeFilter
			title="菜单列表"
			ref="menuRef"
			label="menuName"
			id="menuId"
			children="children"
			:defaultValue="defaultMenuValue"
            :data="treeDatas"
			@change="changeMenuTreeFilter"
		/>



		<div class="table-box" style="flex: 1; width: 0px">
			<ProTable
				ref="powerTable"
				title="权限列表"
				row-key="id"
				:columns="columns"
				:init-param="initParam"
				:request-api="getPowerApi"
			>
				<!-- 表格Header按钮 -->
				<template #tableHeader>
					<el-button type="primary" :icon="CirclePlus" @click="openPowerDialog('新增', {})">新增权限</el-button>
				</template>
				<!-- 表格操作 -->
				<template #operation="scope">
					<!-- 超级管理员无操作 -->
					<template v-if="scope.row.userId != 1">
						<el-button type="primary" link :icon="View" @click="openPowerDialog('查看', scope.row)">查看</el-button>
						<el-button type="primary" link :icon="EditPen" @click="openPowerDialog('编辑', scope.row)">编辑</el-button>
						<el-button type="danger" link :icon="Delete" @click="deletePower(scope.row)">删除</el-button>
					</template>
				</template>
			</ProTable>
		</div>










		<!-- 弹窗 -->
		<el-dialog v-model="powerVisible" :title="powerTitle" :destroy-on-close="true" width="30%" draggable>
			<el-form label-width="100px" ref="powerFormRef" label-suffix=" :" :model="powerFormModel" :disabled="powerTitle == '查看'">
				<el-form-item label="归属菜单">{{ powerFormModel.menuName }} </el-form-item>
                <el-form-item
                        label="权限路径"
                        prop="powerUrl"
                        :rules="[
						{
							required: true,
							message: '请填写权限路径名称',
							trigger: 'blur'
						}
					]"
                >
                    <el-input v-model="powerFormModel.powerUrl" clearable placeholder="请填写权限路径名称"></el-input>
                </el-form-item>
				<el-form-item
					label="权限标识"
					prop="powerCode"
					:rules="[
						{
							required: true,
							message: '请填写权限标识名称',
							trigger: 'blur'
						}
					]"
				>
					<el-input v-model="powerFormModel.powerCode" clearable placeholder="请填写权限标识名称"></el-input>
				</el-form-item>

				<el-form-item
				label="角色"
				prop="roleIds"
				:rules="[
				{
				required: true,
				message: '请选择角色',
				trigger: 'blur'
				}
				]"
				>
				<el-select v-model="powerFormModel.roleIds" multiple style="width: 100%" placeholder="请选择角色">
				<el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
				</el-select>
				</el-form-item>

				<el-form-item
						label="状态"
						prop="enable"
				>
					<el-switch
							v-model="powerFormModel.enable"
							active-color="#13ce66"
							inactive-color="#ff4949"
							active-text="启用"
							inactive-text="禁用"
							active-value="1"
							inactive-value="0"
					>
					</el-switch>
				</el-form-item>

				<el-form-item label="排序" prop="sort">
					<el-input-number
							v-model="powerFormModel.sort"
							placeholder="请填写序号"
							clearable
							controls-position="right"
							:min="1"
					></el-input-number>
				</el-form-item>

				<el-form-item label="备注">
				<el-input v-model="powerFormModel.remark" placeholder="请填写备注" :rows="4" type="textarea"></el-input>
				</el-form-item>
				<!--<el-form-item-->
					<!--label="用户昵称"-->
					<!--prop="nickName"-->
					<!--:rules="[-->
						<!--{-->
							<!--required: true,-->
							<!--message: '请填写用户昵称',-->
							<!--trigger: 'blur'-->
						<!--}-->
					<!--]"-->
				<!--&gt;-->
					<!--<el-input v-model="userFormModel.nickName" clearable placeholder="请填写用户昵称"></el-input>-->
				<!--</el-form-item>-->
				<!--<el-form-item-->
					<!--label="密码"-->
					<!--prop="password"-->
					<!--:rules="[-->
						<!--{-->
							<!--required: true,-->
							<!--message: '请填写密码',-->
							<!--trigger: 'blur'-->
						<!--}-->
					<!--]"-->
					<!--v-if="userTitle == '新增'"-->
				<!--&gt;-->
					<!--<el-input v-model="userFormModel.password" clearable placeholder="请填写密码" type="password" show-password></el-input>-->
				<!--</el-form-item>-->

				<!--<el-form-item label="备注">-->
					<!--<el-input v-model="userFormModel.remark" placeholder="请填写备注" :rows="4" type="textarea"></el-input>-->
				<!--</el-form-item>-->
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="powerVisible = false">{{ powerTitle == "查看" ? "关闭" : "取消" }}</el-button>
					<el-button type="primary" @click="handleSubmit" v-if="powerTitle != '查看'">确认</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 重置密码 -->
		<!--<el-dialog v-model="resetVisible" title="重置密码" :destroy-on-close="true" width="30%" draggable>-->
			<!--<el-form label-width="100px" ref="resetFormRef" label-suffix=" :" :model="resetModel">-->
				<!--<el-form-item-->
					<!--label="新密码"-->
					<!--prop="password"-->
					<!--:rules="[-->
						<!--{-->
							<!--required: true,-->
							<!--message: '请填写新密码',-->
							<!--trigger: 'blur'-->
						<!--}-->
					<!--]"-->
				<!--&gt;-->
					<!--<el-input v-model="resetModel.password" clearable placeholder="请填写新密码"></el-input>-->
				<!--</el-form-item>-->
			<!--</el-form>-->
			<!--<template #footer>-->
				<!--<span class="dialog-footer">-->
					<!--<el-button @click="resetVisible = false">关闭</el-button>-->
					<!--<el-button type="primary" @click="handleResetSubmit">确认</el-button>-->
				<!--</span>-->
			<!--</template>-->
		<!--</el-dialog>-->
	</div>
</template>

<script lang="tsx" setup name="userManage">
import TreeFilter from "@/components/TreeFilter/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Setting } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { getMenuListApi } from "@/api/modules/test/menu";
import { getPowerApi ,addPowerApi,deletePowerApi} from "@/api/modules/test/auth";
import { getRoleListApi } from "@/api/modules/test/role";

import { ElMessage, FormInstance } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";


const menuRef = ref();

// 弹窗菜单树默认选项
let defaultMenuValue = ref<any>([]);

const selectMenuId = ref("");
const selectMenuName = ref("");

const changeMenuTreeFilter = (val: string,labelName: string) => {
	initParam.menuId = val;
	selectMenuId.value=val;
	selectMenuName.value=labelName;
};

const powerTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ menuId: "" });

// 表单配置项
const columns: ColumnProps[] = [
	{
		type: "index",
		label: "序号",
		width: 150
	},
	{
		prop: "powerUrl",
		label: "权限路径",
		search: {
			el: "input"
		}
	},
    {
		prop: "powerCode",
		label: "权限标识",
		search: {
			el: "input"
		}
	},
	{
		prop: "remark",
		label: "备注"
	},
	{
		prop: "enable",
		label: "状态",
		enum: [
			{
				label: "禁用",
				value: '0'
			},
			{
				label: "启用",
				value: '1'
			}
		],
		render: scope => {
			// 渲染tag
			return <el-tag type={scope.row.enable == '1' ? "success" : "danger"}>{scope.row.enable == '1' ? "启用" : "禁用"}</el-tag>;
		}
	},
	{
		prop: "createTime",
		label: "注册时间"
	},
	{
		prop: "sort",
		label: "排序"
	},
	{
		prop: "operation",
		label: "操作",
		width: 350,
		fixed: "right"
	}
];

const powerVisible = ref(false);
const powerTitle = ref("");
const powerFormRef = ref<FormInstance>();
const powerFormModel = ref({
	id:"",
	menuName: "",
	menuId: "",
    powerUrl:"",
	powerCode: "",
	remark: "",
	enable: "",
	sort: "",
	create_time: "",
	roleIds: []
});

const roleOptions = ref<any>([]);

const openPowerDialog = async (title: string, row: any = {}) => {
	powerVisible.value = true;
	powerTitle.value = title;
	// 获取角色列表
	const { result } = await getRoleListApi({ pageNum: 1, pageSize: 9999 });
	roleOptions.value = (result as any).records;
	roleOptions.value.forEach(k => {
		k.roleId = k.roleId+"";
	})
	if (title == "新增") {
		powerFormModel.value = { ...row, menuId: selectMenuId.value, menuName: selectMenuName.value };
	} else {
		powerFormModel.value = {...row, roleIds: row.roleId.split(",")};

	}
};

// 提交
const handleSubmit = () => {
	powerFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			console.log(powerFormModel.value)
			const data = await addPowerApi({...powerFormModel.value, roleId: powerFormModel.value.roleIds.join(",")});
			ElMessage.success({ message: data.message });
			powerTable.value.getTableList();
			powerVisible.value = false;
		} catch (err) {
			console.log(err);
		}
	});
};

const treeDatas = ref([]);

// 获取部门
const getMenuDatas = async () => {
	const { result } = await getMenuListApi({});
    treeDatas.value = [
        {
            menuId: "",
            menuName: "根目录",
            children: result
        }
    ]
};


// 删除权限
const deletePower = async (val: any) => {
	await useHandleData(deletePowerApi, { id: val.id }, "删除权限");
	powerTable.value.getTableList();
};


// 初始化请求
onMounted(async () => {
	await getMenuDatas();
});
</script>
<style lang="scss" scoped>
.content-box {
	display: flex;
	flex-direction: row;
	align-items: flex-start;

	.content-table {
		flex: 1;
		height: 100%;
	}
}
</style>
